package com.oxygen.pt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.oxygen.pt.mapper.UserMapper;
import com.oxygen.pt.pojo.dto.LoginFormDTO;
import com.oxygen.pt.pojo.dto.UserDTO;
import com.oxygen.pt.pojo.entity.User;
import com.oxygen.pt.pojo.vo.Result;
import com.oxygen.pt.service.UserService;
import com.oxygen.pt.utils.RedisConstants;
import com.oxygen.pt.utils.RedisIdWorker;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.session.Session;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisIdWorker redisIdWorker;

    @Override
    public Result<String> login(LoginFormDTO loginFormDTO) {
        if (loginFormDTO == null){
            return Result.error("请填写账号和密码");
        }
        //根据传来的信息查找数据库中的密码，
        String account = loginFormDTO.getAccount();
        User user = userMapper.queryByAccount(account);
        //账号密码是否正确，正确的话能够查询到用户的信息
        //system.out.println(user.toString());
        if (user == null){
            return Result.error("账户不存在");
        }
        if (!user.getPassword().equals(loginFormDTO.getPassword())){
            //如果密码错误
            return Result.error("密码错误");
        }
        //存储到缓存中
        String token  = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY,token);
        //生成token 返回给前端
        return Result.success(token);
    }

    @Override
    public Result<String> addUser(UserDTO userDTO) {
        if (userDTO == null){
            return Result.error("信息填写错误");
        }
        //填写正确 添加到数据库

        User user = BeanUtil.copyProperties(userDTO, User.class);
        //调用Mapper层添加数据
        //TODO: 如何实现避免重复添加
        user.setUserId(String.valueOf(redisIdWorker.nextId(RedisConstants.USER_ID)));
        user.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
        user.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
        userMapper.addUser(user);
        return Result.success("成功添加");
    }
}
